package com.example.jpgstreamdemo;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;

public class MainActivity extends Activity {
	
	private static final String TAG = "wenhao";
	private static final String IPADDRESS = "172.20.223.152";
	private static final int PORT = 9000; 
	private Thread thread;
	
	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;
	private boolean mRunflag = true;
	
	private String urlContent = "GET /?action=stream HTTP/1.1\r\n"
			+ "User-Agent: Cambozola V0.68-0041/Java 1.6.0_31 Sun Microsystems Inc.\r\n"
			+ "Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2\r\n"
			+ "Connection: keep-alive\r\n"
			+ "\r\n";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		
		mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
		mSurfaceHolder = mSurfaceView.getHolder();
		mSurfaceHolder.setFixedSize(320, 240); //设置surfaceview的大小
		
		mSurfaceHolder.addCallback(new Callback() {

			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				// TODO Auto-generated method stub
				Log.d(TAG, "surfaceDestroyed...");
				
				stop(null);
			}

			@Override
			public void surfaceCreated(SurfaceHolder holder) {
				// TODO Auto-generated method stub
				Log.d(TAG, "surfaceCreated...");

			}
			
			@Override
			public void surfaceChanged(SurfaceHolder holder, int format,
					int width, int height) {
				// TODO Auto-generated method stub
				Log.d(TAG, "surfaceChanged...");
			}
		});
	}
	
	public void start(View view){
		
		mRunflag = true;
		thread = new Thread(){
			
			public void run(){
				
				tcp();
			}
			
		};
		
		thread.start();
	}
	
	public void stop(View view){
		
		mRunflag = false;		
		if (thread == null) {
			throw new IllegalStateException(
					"Cannot stop proxy; it has not been started.");
		}

		thread.interrupt();
		try {
			thread.join(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	
	private void tcp(){
		
		Socket socket = null;
		try {
			socket = new Socket(InetAddress.getByName(IPADDRESS), PORT);
			OutputStream os = socket.getOutputStream();
			InputStream is = socket.getInputStream();
			
			os.write(urlContent.getBytes());			
			
			parseStream2Bitmap(is);	
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {				
				if(socket != null){
					socket.close();
				}			
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	/**
	 * 
	 * 解析流当中的bitmap图片
	 * 
	 * @param is
	 * @return
	 */
	private Bitmap parseStream2Bitmap(InputStream is){
		
		ByteArrayBuffer byteBuffer = null;
		byte[] buffer = new byte[5*1024];
		int totalLen = 0;
		int len = 0;

		try {
			while(mRunflag){
				len = is.read(buffer);
				String tmp = new String(buffer, 0, len);
				if(tmp.contains("Content-Length")){
					
					//Log.d(TAG, "------------\r\ntmp = " + tmp);
					if(byteBuffer != null){
						
						int endNum = tmp.indexOf("Content-Length");
						byteBuffer.append(buffer, 0, endNum);
						//在surfaceview中画图
						//Log.d(TAG,"total = " + totalLen + " byteLen = " + byteBuffer.length());
						BitmapFactory.Options ops = new BitmapFactory.Options();
						ops.inSampleSize = 2;
						//Bitmap bitmap =  BitmapFactory.decodeByteArray(byteBuffer.toByteArray(), 0, byteBuffer.length(), ops);
						
						Bitmap bitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(byteBuffer.toByteArray(), 0, byteBuffer.length()),null,ops);
						if(bitmap != null){
							//Log.d(TAG, bitmap.getWidth()+":"+bitmap.getHeight());
							draw(bitmap);
							bitmap.recycle();
						}
						
					}

					//重新下一张图片
					totalLen = getPicLength(tmp);
					
					byteBuffer = new ByteArrayBuffer(totalLen);
					int startNum = tmp.lastIndexOf("\r\n");
					//Log.d(TAG,"startNum = " + startNum);
					//Log.d(TAG, totalLen+":"+(startNum+2)+":"+(len-startNum-2));
					//Log.d(TAG,"data = " + new String(buffer, startNum+2, len - startNum -2));
					byteBuffer.append(buffer, startNum+2, len - startNum - 2);
				}else{
					
					if(byteBuffer != null){
						byteBuffer.append(buffer, 0, len);
					}
				}
				
				
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * 
	 * 切割发送过流文件，并获取其中的文件大小
	 * 
	 * @param str
	 * @return
	 */
	private int getPicLength(String str){
		int len = 0;
		
		Pattern p = Pattern.compile("Content-Length: (\\d+)\r\n");
		Matcher m = p.matcher(str);
		while(m.find()) {
			len = Integer.valueOf(m.group(1));
		}
		
	//	Log.d("wenhao","len = " + len);
		return len;
	}
	
	/**
	 * 在surfaceView当中绘制bitmap
	 * @param temp
	 */
	private void draw(Bitmap temp){
		
		Canvas canvas = mSurfaceHolder.lockCanvas();
		if(canvas == null){
			return;
		}
		Paint p = new Paint();
		//canvas.drawRect(10, 10, 100, 100, p);
		canvas.drawBitmap(temp, 0, 0, p);
		mSurfaceHolder.unlockCanvasAndPost(canvas);
	}
}
